<?php

namespace HuangYi\Rbac\Models;

use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Support\Facades\Config;
use Ramsey\Uuid\Uuid;

abstract class Model extends BaseModel
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'description'];

    /**
     * Create a new Eloquent model instance.
     *
     * @param  array  $attributes
     */
    public function __construct(array $attributes = [])
    {
        $this->keyType = Config::get('rbac.key_type');
        $this->incrementing = $this->keyType !== 'uuid';

        parent::__construct($attributes);
    }

    /**
     * Forget caches.
     */
    abstract public function forgetCaches();

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        self::creating(function (self $model) {
            if ($model->getKeyType() === 'uuid' && ! Uuid::isValid($model->getKey())) {
                $model->setAttribute($model->getKeyName(), Uuid::uuid4());
            }
        });

        self::updated(function (self $model) {
            $model->forgetCaches();
        });

        self::deleted(function (self $model) {
            $model->forgetCaches();
        });
    }
}
